<%@ page import="java.awt.*" %>
<%@ page import="java.util.Random" %>
<%@ page import="java.awt.image.BufferedImage" %>
<%@ page import="javax.imageio.ImageIO" %>
<%@ page contentType="image/jpeg;charset=UTF-8" language="java" %>


<%!
    //随机产生颜色值
    public Color getColor(){
        Random ran = new Random() ;//Math.random()  0-1
        int r = ran.nextInt(256) ;
        int g = ran.nextInt(256) ;
        int b = ran.nextInt(256) ;
        return new Color(r,g,b) ;//red green blue  0-255
    }

    //产生验证码值
    public String getNum()
    {
        String ss="A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
        String arr[]=ss.split(",");//将字符串转成数组
        //随机生成2个字母和2个数字 如：A0B9
        Random ran=new Random();
        int one=ran.nextInt(52);
        int two=ran.nextInt(10);
        int three=ran.nextInt(52);
        int four=ran.nextInt(10);
        StringBuffer s=new StringBuffer();
        s.append(arr[one]);//随机生成的0-26的数字作为数组索引，将该索引处的字母追加到Stringbuffer中
        s.append(two);//直接把数字放到StringBuffer里，可以用。
        s.append(arr[three]);
        s.append(four);//直接把数字放到StringBuffer里，可以用。

        //之前的生成四位数字的方法  0-8999   1000-9999
        // int ran = (int)( Math.random()*9000) +1000 ;
        return s.toString();
    }
%>

<%

    //禁止缓存，防止验证码过期
    response.setHeader("Pragma","no-cache");
    response.setHeader("Cache-Control","no-cache");
    response.setHeader("Expires","0");

    //绘制验证码
    BufferedImage image = new BufferedImage(120,40,BufferedImage.TYPE_INT_RGB) ;
    //画笔
    Graphics graphics = image.getGraphics();
    graphics.fillRect(0,0,120,40);
    //绘制干扰线条
    for(int i=0;i<50;i++)
    {
        Random ran = new Random() ;
        int xBegin = ran.nextInt(120) ;//55
        int yBegin = ran.nextInt(40) ;

        int xEnd = ran.nextInt(xBegin +50 ) ;
        int yEnd = ran.nextInt(yBegin + 50) ;

        graphics.setColor( getColor());
        //绘制线条
        graphics.drawLine(xBegin,yBegin,xEnd,yEnd);
    }

    graphics.setFont(new Font("seif",Font.BOLD,35));
    //绘制验证码
    graphics.setColor(getColor());
    String checkCode = getNum() ; //2 1 3 4
    StringBuffer sb = new StringBuffer() ;
    for(int i=0;i<checkCode.length();i++){
        sb.append(checkCode.charAt(i)+""  )  ;//验证码的每一位数字
    }

    graphics.drawString( sb.toString(), 0,30 );//绘制验证码

    //将验证码真实值 保存在session中，供使用时比较真实性
    session.setAttribute("CKECKCODE"  ,checkCode );

    //真实的产生图片
    ImageIO.write(image,"jpeg",  response.getOutputStream()) ;

    //关闭
    out.clear();
    out = pageContext.pushBody() ;  //<input type="image" src="xxx" />



%>